/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.gzchengguo.cn

 */
package link.chengguo.orangemall.modules.shop.rest;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import link.chengguo.orangemall.constant.ShopConstants;
import link.chengguo.orangemall.exception.BadRequestException;
import link.chengguo.orangemall.logging.aop.log.Log;
import link.chengguo.orangemall.modules.aop.ForbidSubmit;
import link.chengguo.orangemall.modules.shop.domain.OrangeSystemGroupData;
import link.chengguo.orangemall.modules.shop.service.OrangeSystemGroupDataService;
import link.chengguo.orangemall.modules.shop.service.dto.OrangeSystemGroupDataQueryCriteria;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author chengguo
* @date 2019-10-18
*/
@Api(tags = "商城:数据配置管理")
@RestController
@RequestMapping("api")
public class SystemGroupDataController {

    private final OrangeSystemGroupDataService orangeSystemGroupDataService;

    public SystemGroupDataController(OrangeSystemGroupDataService orangeSystemGroupDataService) {
        this.orangeSystemGroupDataService = orangeSystemGroupDataService;
    }

    @Log("查询数据配置")
    @ApiOperation(value = "查询数据配置")
    @GetMapping(value = "/orangeSystemGroupData")
    @PreAuthorize("hasAnyRole('admin','ORANGESYSTEMGROUPDATA_ALL','ORANGESYSTEMGROUPDATA_SELECT')")
    public ResponseEntity getOrangeSystemGroupDatas(OrangeSystemGroupDataQueryCriteria criteria,
                                                Pageable pageable){
        Sort sort = new Sort(Sort.Direction.DESC, "sort");
        Pageable pageableT = PageRequest.of(pageable.getPageNumber(),
                pageable.getPageSize(),
                sort);
        return new ResponseEntity<>(orangeSystemGroupDataService.queryAll(criteria,pageableT),HttpStatus.OK);
    }

    @ForbidSubmit
    @Log("新增数据配置")
    @ApiOperation(value = "新增数据配置")
    @PostMapping(value = "/orangeSystemGroupData")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','ORANGESYSTEMGROUPDATA_ALL','ORANGESYSTEMGROUPDATA_CREATE')")
    public ResponseEntity create(@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        this.checkParam(jsonObject);

        OrangeSystemGroupData orangeSystemGroupData = new OrangeSystemGroupData();
        orangeSystemGroupData.setGroupName(jsonObject.get("groupName").toString());
        jsonObject.remove("groupName");
        orangeSystemGroupData.setValue(jsonObject.toJSONString());
        orangeSystemGroupData.setStatus(jsonObject.getInteger("status"));
        orangeSystemGroupData.setSort(jsonObject.getInteger("sort"));


        return new ResponseEntity<>(orangeSystemGroupDataService.save(orangeSystemGroupData),HttpStatus.CREATED);
    }

    @ForbidSubmit
    @Log("修改数据配置")
    @ApiOperation(value = "修改数据配置")
    @PutMapping(value = "/orangeSystemGroupData")
    @CacheEvict(cacheNames = ShopConstants.ORANGEMALL_REDIS_INDEX_KEY,allEntries = true)
    @PreAuthorize("hasAnyRole('admin','ORANGESYSTEMGROUPDATA_ALL','ORANGESYSTEMGROUPDATA_EDIT')")
    public ResponseEntity update(@RequestBody String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        this.checkParam(jsonObject);

        OrangeSystemGroupData orangeSystemGroupData = new OrangeSystemGroupData();

        orangeSystemGroupData.setGroupName(jsonObject.get("groupName").toString());
        jsonObject.remove("groupName");
        orangeSystemGroupData.setValue(jsonObject.toJSONString());
        if(jsonObject.getInteger("status") == null){
            orangeSystemGroupData.setStatus(1);
        }else{
            orangeSystemGroupData.setStatus(jsonObject.getInteger("status"));
        }

        if(jsonObject.getInteger("sort") == null){
            orangeSystemGroupData.setSort(0);
        }else{
            orangeSystemGroupData.setSort(jsonObject.getInteger("sort"));
        }


        orangeSystemGroupData.setId(Integer.valueOf(jsonObject.get("id").toString()));
        orangeSystemGroupDataService.saveOrUpdate(orangeSystemGroupData);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @ForbidSubmit
    @Log("删除数据配置")
    @ApiOperation(value = "删除数据配置")
    @DeleteMapping(value = "/orangeSystemGroupData/{id}")
    @PreAuthorize("hasAnyRole('admin','ORANGESYSTEMGROUPDATA_ALL','ORANGESYSTEMGROUPDATA_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id){
        orangeSystemGroupDataService.removeById(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 检测参数
     * @param jsonObject
     */
    private void checkParam(JSONObject jsonObject){
        if(ObjectUtil.isNotNull(jsonObject.get("name"))){
            if(StrUtil.isEmpty(jsonObject.getString("name"))){
                throw new BadRequestException("名称必须填写");
            }
        }

        if(ObjectUtil.isNotNull(jsonObject.get("title"))){
            if(StrUtil.isEmpty(jsonObject.getString("title"))){
                throw new BadRequestException("标题必须填写");
            }
        }

        if(ObjectUtil.isNotNull(jsonObject.get("pic"))){
            if(StrUtil.isEmpty(jsonObject.getString("pic"))){
                throw new BadRequestException("图片必须上传");
            }
        }


        if(ObjectUtil.isNotNull(jsonObject.get("info"))){
            if(StrUtil.isEmpty(jsonObject.getString("info"))){
                throw new BadRequestException("简介必须填写");
            }
        }

    }
}
